package edu.vital.energy.longevity.ch08.controller;

import edu.vital.energy.longevity.ch08.domain.Article;
import edu.vital.energy.longevity.ch08.mapper.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/articles")
public class ArticleController {

    @Autowired
    private ArticleMapper articleMapper;

    // 查询所有文章
    @GetMapping
    public String getAllArticles(Model model) {
        model.addAttribute("articles", articleMapper.selectList(null));
        return "article";
    }

    // 根据ID查询文章（用于更新）
    @GetMapping("/{id}")
    public String getArticleById(@PathVariable Integer id, Model model) {
        Article article = articleMapper.selectById(id);
        if (article != null) {
            model.addAttribute("article", article);
            return "updateArticle"; // 跳转到更新文章页面
        } else {
            model.addAttribute("message", "文章未找到");
            return "error"; // 跳转到错误页面
        }
    }

    // 新增文章
    @PostMapping
    public String addArticle(@ModelAttribute Article article) {
        articleMapper.insert(article);
        return "redirect:/articles";
    }

    // 修改文章
    @PutMapping("/{id}")
    public String updateArticle(@PathVariable Integer id, @ModelAttribute Article article) {
        article.setId(id);
        articleMapper.updateById(article);
        return "redirect:/articles";
    }

    // 删除文章
    @DeleteMapping("/{id}")
    public String deleteArticle(@PathVariable Integer id) {
        articleMapper.deleteById(id);
        return "redirect:/articles";
    }
}